<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['content:category:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="categoryList"
      row-key="categoryId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="栏目名称" prop="categoryName" />
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="栏目图标" align="center" prop="icon" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.icon" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_notice_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!-- 新增状态开关列 -->
      <el-table-column label="状态开关" align="center" width="100">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              :active-value="'0'"
              :inactive-value="'1'"
              @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['content:category:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['content:category:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['content:category:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改栏目管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="categoryRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="栏目名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入栏目名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="栏目图标" prop="icon">
          <image-upload v-model="form.icon"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_notice_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Category">
import {
  listCategory,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
  updateCategoryStatus
} from "@/api/content/category"

const { proxy } = getCurrentInstance()
const { sys_notice_status } = proxy.useDict('sys_notice_status')

const categoryList = ref([])
const categoryOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const isExpandAll = ref(true)
const refreshTable = ref(true)

const data = reactive({
  form: {},
  queryParams: {
  },
  rules: {
    categoryName: [
      { required: true, message: "栏目名称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询栏目管理列表 */
function getList() {
  loading.value = true
  listCategory(queryParams.value).then(response => {
    categoryList.value = proxy.handleTree(response.data, "categoryId", "parentId")
    loading.value = false
  })
}

/** 查询栏目管理下拉树结构 */
function getTreeselect() {
  listCategory().then(response => {
    categoryOptions.value = []
    const data = { categoryId: 0, categoryName: '顶级节点', children: [] }
    data.children = proxy.handleTree(response.data, "categoryId", "parentId")
    categoryOptions.value.push(data)
  })
}
	
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    categoryId: null,
    categoryName: null,
    parentId: null,
    level: null,
    sortOrder: null,
    icon: null,
    status: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("categoryRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  getTreeselect()
  if (row != null && row.categoryId) {
    form.value.parentId = row.categoryId
  } else {
    form.value.parentId = 0  // 确保parentId有默认值
  }
  open.value = true
  title.value = "添加栏目管理"
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  await getTreeselect()
  if (row != null) {
    form.value.parentId = row.parentId
  }
  getCategory(row.categoryId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改栏目管理"
  })
}

/** 状态开关变更 */
function handleStatusChange(row) {
  const status = row.status
  const statusText = status === '0' ? '启用' : '停用'

  // 如果改为关闭状态，需要递归关闭所有子栏目
  if (status === '1') {
    proxy.$modal.confirm(`确定要${statusText}栏目"${row.categoryName}"及其所有子栏目吗？`).then(() => {
      updateCategoryStatus(row.categoryId, status, true).then(() => {
        proxy.$modal.msgSuccess(`${statusText}成功`)
        getList()
      })
    }).catch(() => {
      // 操作取消，恢复原来的状态
      row.status = status === '0' ? '1' : '0'
    })
  } else {
    // 启用状态只修改当前栏目
    checkParentStatusForSwitch(row, statusText);
  }
}

/** 检查父栏目状态（用于开关变更） */
function checkParentStatusForSwitch(row, statusText) {
  // 如果是顶级栏目，直接启用
  if (row.parentId === 0) {
    updateCategoryStatus(row.categoryId, '0', false).then(() => {
      proxy.$modal.msgSuccess(`${statusText}成功`)
    }).catch(() => {
      row.status = '1'
    })
    return;
  }

  // 检查父栏目状态
  getCategory(row.parentId).then(response => {
    const parentCategory = response.data;
    if (parentCategory.status === '0') {
      // 父栏目正常，直接启用当前栏目
      updateCategoryStatus(row.categoryId, '0', false).then(() => {
        proxy.$modal.msgSuccess(`${statusText}成功`)
      }).catch(() => {
        row.status = '1'
      })
    } else {
      // 父栏目停用，提示用户
      proxy.$modal.confirm(
          `父栏目"${parentCategory.categoryName}"处于停用状态，是否将其启用并递归启用所有祖先栏目？`
      ).then(() => {
        // 用户选择是，递归启用父栏目和当前栏目
        updateCategoryStatus(row.parentId, '0', true).then(() => {
          updateCategoryStatus(row.categoryId, '0', false).then(() => {
            proxy.$modal.msgSuccess(`${statusText}成功`)
            getList()
          })
        })
      }).catch(() => {
        // 用户选择否，恢复原来的状态
        row.status = '1'
        proxy.$modal.msgError(`${statusText}失败：父栏目处于停用状态`)
      })
    }
  }).catch(() => {
    // 获取父栏目信息失败，直接启用
    updateCategoryStatus(row.categoryId, '0', false).then(() => {
      proxy.$modal.msgSuccess(`${statusText}成功`)
    }).catch(() => {
      row.status = '1'
    })
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categoryRef"].validate(valid => {
    if (valid) {

      // 如果改为关闭状态，需要递归关闭所有子栏目
      if (form.value.status === '1') {
        proxy.$modal.confirm(`确定要停用栏目"${form.value.categoryName}"及其所有子栏目吗？`).then(() => {
          updateCategoryStatus(form.value.categoryId, form.value.status, true).then(() => {
            performSubmit();
          })
        })
      }else {
        checkParentStatusAndSubmit();
      }
    }
  })
}

/** 检查父栏目状态并提交 */
function checkParentStatusAndSubmit() {
  // 如果是顶级栏目，直接提交
  if (form.value.parentId === 0) {
    performSubmit();
    return;
  }

  // 检查父栏目状态
  getCategory(form.value.parentId).then(response => {
    const parentCategory = response.data;
    if (parentCategory.status === '0') {
      // 父栏目正常，直接提交
      performSubmit();
    } else {
      // 父栏目停用，提示用户
      proxy.$modal.confirm(
          `父栏目"${parentCategory.categoryName}"处于停用状态，是否将其启用并递归启用所有祖先栏目？`
      ).then(() => {
        // 用户选择是，递归启用父栏目
        updateCategoryStatus(form.value.parentId, '0', true).then(() => {
          performSubmit();
        });
      }).catch(() => {
        // 用户选择否
        if (form.value.categoryId != null) {
          // 修改操作，取消修改
          proxy.$modal.msgError("修改失败：父栏目处于停用状态");
        } else {
          // 新增操作，将状态改为停用后新增
          const originalStatus = form.value.status;
          form.value.status = '1';
          performSubmit().then(() => {
            proxy.$modal.msgSuccess("新增成功，但由于父栏目停用，当前栏目状态已设置为停用");
            // 恢复原始状态值，避免影响表单显示
            form.value.status = originalStatus;
          });
        }
      });
    }
  }).catch(() => {
    // 获取父栏目信息失败，直接提交
    performSubmit();
  });
}


/** 执行提交操作 */
function performSubmit() {
  return new Promise((resolve, reject) => {
    if (form.value.categoryId != null) {
      updateCategory(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
        resolve();
      }).catch(reject);
    } else {
      addCategory(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
        resolve();
      }).catch(reject);
    }
  });
}

/** 删除按钮操作 */
// function handleDelete(row) {
//   proxy.$modal.confirm('是否确认删除栏目管理编号为"' + row.categoryId + '"的数据项？').then(function() {
//     return delCategory(row.categoryId)
//   }).then(() => {
//     getList()
//     proxy.$modal.msgSuccess("删除成功")
//   }).catch(() => {})
// }
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除栏目"' + row.categoryName + '"及其所有子栏目？').then(function() {
    return delCategory(row.categoryId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
getList()
</script>
